<script>
	/**
	 * vuex管理登录状态，具体可以参考官方登录模板示例
	 */
	import {
		mapMutations
	} from "vuex";
	import APPUpdate from "@/plugins/APPUpdate";
	import {
		getClipboardData
	} from "@/js_sdk/h5-copy/h5-copy.js";
	import {
		getUserInfo,
		VIPRateSetting
	} from "@/api/members";
	import config from "@/config/config";
	import storage from "@/utils/storage.js";
	// 悬浮球
	// require("sdk/libs/strophe");
	let WebIM = (wx.WebIM = require("./utils/WebIM")["default"]);
	let msgStorage = require("./components/chat/msgstorage");
	let msgType = require("./components/chat/msgtype");
	let disp = require("./utils/broadcast");
	let logout = false;

	function ack(receiveMsg) {
		// 处理未读消息回执
		var bodyId = receiveMsg.id; // 需要发送已读回执的消息id

		var ackMsg = new WebIM.message("read", WebIM.conn.getUniqueId());
		ackMsg.set({
			id: bodyId,
			to: receiveMsg.from,
		});
		WebIM.conn.send(ackMsg.body);
	}

	function onMessageError(err) {
		if (err.type === "error") {
			uni.showToast({
				title: err.errorText,
			});
			return false;
		}

		return true;
	}

	function getCurrentRoute() {
		let pages = getCurrentPages();
		if (pages.length > 0) {
			let currentPage = pages[pages.length - 1];
			return currentPage.route;
		}
		return "/";
	}

	// 包含陌生人版本
	function calcUnReadSpot(message) {
		let myName = uni.getStorageSync("myUsername");
		uni.getStorageInfo({
			success: function(res) {
				let storageKeys = res.keys;
				let newChatMsgKeys = [];
				let historyChatMsgKeys = [];
				storageKeys.forEach((item) => {
					if (item.indexOf(myName) > -1 && item.indexOf("rendered_") == -1) {
						newChatMsgKeys.push(item);
					}
				});
				let count = newChatMsgKeys.reduce(function(result, curMember, idx) {
					let chatMsgs;
					chatMsgs = uni.getStorageSync(curMember) || [];
					return result + chatMsgs.length;
				}, 0);

				getApp().globalData.unReadMessageNum = count;
				disp.fire("em.unreadspot", message);
			},
		});
	}

	function saveGroups() {
		var me = this;
		return WebIM.conn.getGroup({
			limit: 50,
			success: function(res) {
				uni.setStorage({
					key: "listGroup",
					data: res.data,
				});
			},
			error: function(err) {
				console.log(err);
			},
		});
	}

	export default {
		data() {
			return {
				config,
			};
		},

		globalData: {
			unReadMessageNum: 0,
			userInfo: null,
			saveFriendList: [],
			saveGroupInvitedList: [],
			isIPX: false, //是否为iphone X
			conn: {
				closed: false,
				curOpenOpt: {},
				open(opt) {
					uni.showLoading({
						title: "正在初始化客户端..",
						mask: true,
					});
					this.curOpenOpt = opt;
					WebIM.conn.open(opt);
					this.closed = false;
				},

				reopen() {
					if (this.closed) {
						//this.open(this.curOpenOpt);
						WebIM.conn.open(this.curOpenOpt);
						this.closed = false;
					}
				},
			},
			onLoginSuccess: function(myName) {
				uni.hideLoading();
				uni.redirectTo({
					url: "/pages/chat/chat?myName=" + myName,
				});
			},

			getUserInfo(cb) {
				var me = this;

				if (this.userInfo) {
					typeof cb == "function" && cb(this.userInfo);
				} else {
					// 调用登录接口
					uni.login({
						success() {
							uni.getUserInfo({
								success(res) {
									me.userInfo = res.userInfo;
									typeof cb == "function" && cb(me.userInfo);
								},
							});
						},
					});
				}
			},

			checkIsIPhoneX: function() {
				const me = this;
				uni.getSystemInfo({
					success: function(res) {
						// 根据 model 进行判断
						if (res.model && res.model.search("iPhone X") != -1) {
							me.isIPX = true;
						}
					},
				});
			},
		},

		/**
		 * 监听返回
		 */
		onBackPress(e) {
			if (e.from == "backbutton") {
				let routes = getCurrentPages();
				let curRoute = routes[routes.length - 1].options;
				routes.forEach((item) => {
					if (
						item.route == "pages/tabbar/cart/cartList" ||
						item.route.indexOf("pages/product/goods") != -1
					) {
						uni.redirectTo({
							url: item.route,
						});
					}
				});

				if (curRoute.addId) {
					uni.reLaunch({
						url: "/pages/tabbar/cart/cartList",
					});
				} else {
					uni.navigateBack();
				}
				return true; //阻止默认返回行为
			}
		},
		methods: {
			...mapMutations(["login"]),
		},
		onLaunch: function() {
			// 判断是否登录 已登录并且用于被禁用直接跳转的登录并提示
			let userInfo = storage.getUserInfo()
			if (userInfo.id) {
				//获取用户信息
				getUserInfo().then((user) => {
					let userInfo = user.data.result
					if (userInfo.disabled == false) {
						this.$options.filters.clearAllStorage()
						uni.reLaunch({
							url: '/pages/passport/wechatMPLogin?tip=1'
						})
					}
				});
			}
			// #ifdef APP-PLUS
			this.checkArguments(); // 检测启动参数
			APPUpdate();

			// 重点是以下： 一定要监听后台恢复 ！一定要
			plus.globalEvent.addEventListener("newintent", (e) => {
				this.checkArguments(); // 检测启动参数
			});
			// #endif

			// #ifdef MP-WEIXIN
			this.applyUpdateWeChat();
			// #endif
			// 调用 API 从本地缓存中获取数据
			// uni.setInnerAudioOption({
			//   obeyMuteSwitch: false
			// });
			var me = this;
			var logs = uni.getStorageSync("logs") || [];
			logs.unshift(Date.now());
			uni.setStorageSync("logs", logs); //

			disp.on("em.main.ready", function() {
				calcUnReadSpot();
			});
			disp.on("em.chatroom.leave", function() {
				calcUnReadSpot();
			});
			disp.on("em.chat.session.remove", function() {
				calcUnReadSpot();
			});
			disp.on("em.chat.audio.fileLoaded", function() {
				calcUnReadSpot();
			});
			disp.on("em.main.deleteFriend", function() {
				calcUnReadSpot();
			});
			disp.on("em.chat.audio.fileLoaded", function() {
				calcUnReadSpot();
			}); //

			WebIM.conn.listen({
				onOpened(message) {
					if (
						getCurrentRoute() == "pages/login/login" ||
						getCurrentRoute() == "pages/login_token/login_token" || getCurrentRoute() ==
						"pages/tabbar/message-notice/message-notice"
					) {
						me.globalData.onLoginSuccess(
							uni.getStorageSync("myUsername").toLowerCase()
						);
					}
				},

				onReconnect() {
					uni.showToast({
						title: "重连中...",
						duration: 2000,
					});
				},

				onSocketConnected() {
					uni.showToast({
						title: "socket连接成功",
						duration: 2000,
					});
				},

				onClosed() {
					// uni.showToast({
					// 	title: "网络已断开",
					// 	icon: "none",
					// 	duration: 2000,
					// });
					// uni.redirectTo({
					// 	url: "../login/login",
					// });
					me.globalData.conn.closed = true;
					WebIM.conn.close();
				},

				onInviteMessage(message) {
					me.globalData.saveGroupInvitedList.push(message);
					disp.fire("em.invite.joingroup", message); // uni.showModal({
					// 	title: message.from + " 已邀你入群 " + message.roomid,
					// 	success(){
					// 		disp.fire("em.invite.joingroup", message);
					// 	},
					// 	error(){
					// 		disp.fire("em.invite.joingroup", message);
					// 	}
					// });
				},

				onReadMessage(message) {
					//console.log('已读', message)
				},

				//onPresence为旧版 ，建议参考最新增删好友api文档 ：http://docs-im.easemob.com/im/web/basics/buddy
				onPresence(message) {

					switch (message.type) {
						case "unsubscribe":
							break;
							// 好友邀请列表
						case "subscribe":
							for (let i = 0; i < me.globalData.saveFriendList.length; i++) {
								if (me.globalData.saveFriendList[i].from === message.from) {
									me.globalData.saveFriendList[i] = message;
									disp.fire("em.subscribe");
									return;
								}
							}
							msgStorage.saveReceiveMsg(message, 'INFORM'); //存添加好友消息，方便展示通知
							me.globalData.saveFriendList.push(message);
							disp.fire("em.subscribe");

							break;

						case "subscribed":
							uni.showToast({
								title: "添加成功",
								duration: 1000,
							});
							disp.fire("em.subscribed");
							break;

						case "unsubscribed":
							disp.fire("em.unsubscribed");
							break;
						case "direct_joined":
							saveGroups();
							uni.showToast({
								title: "已进群",
								duration: 1000,
							});
							break;
						case "memberJoinPublicGroupSuccess":
							saveGroups();
							uni.showToast({
								title: "已进群",
								duration: 1000,
							});
							break;
						case "invite":
							// 防止重复添加
							for (let i = 0; i < me.globalData.saveGroupInvitedList.length; i++) {
								if (me.globalData.saveGroupInvitedList[i].from === message.from) {
									me.globalData.saveGroupInvitedList[i] = message;
									disp.fire("em.invite.joingroup")
									return;
								}
							}
							me.globalData.saveGroupInvitedList.push(message);
							disp.fire("em.invite.joingroup");
							msgStorage.saveReceiveMsg(message, 'INFORM'); //存添加好友消息，方便展示通知
							break;
						case "unavailable":
							disp.fire("em.contacts.remove");
							disp.fire("em.group.leaveGroup", message);
							break;

						case "deleteGroupChat":
							disp.fire("em.invite.deleteGroup", message);
							break;

						case "leaveGroup":
							disp.fire("em.group.leaveGroup", message);
							break;

						case "removedFromGroup":
							disp.fire("em.group.leaveGroup", message);
							break;

						default:
							break;
					}
				},

				onRoster(message) {
					// let pages = getCurrentPages();
					// if(pages[0]){
					// 	pages[0].onShow();
					// }
				},

				onVideoMessage(message) {
					console.log("onVideoMessage: ", message);

					if (message) {
						msgStorage.saveReceiveMsg(message, msgType.VIDEO);
					}

					calcUnReadSpot(message);
					ack(message);
				},

				onAudioMessage(message) {
					console.log("onAudioMessage", message);

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.AUDIO);
						}

						calcUnReadSpot(message);
						ack(message);
					}
				},

				onCmdMessage(message) {
					console.log("onCmdMessage", message);

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.CMD);
						}

						calcUnReadSpot(message);
						ack(message);
					}
				},
				onTextMessage(message) {
					console.log("onTextMessage", message);

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.TEXT);
						}

						calcUnReadSpot(message);
						ack(message);
					}
				},

				onEmojiMessage(message) {
					console.log("onEmojiMessage", message);

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.EMOJI);
						}

						calcUnReadSpot(message);
						ack(message);
					}
				},

				onPictureMessage(message) {
					console.log("onPictureMessage", message);

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.IMAGE);
						}

						calcUnReadSpot(message);
						ack(message);
					}
				},

				onFileMessage(message) {
					console.log("onFileMessage", message);

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.FILE);
						}

						calcUnReadSpot(message);
						ack(message);
					}
				},

				// 各种异常
				onError(error) {
					console.log(error); // 16: server-side close the websocket connection
					// if (error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED) {
					//   // if(error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED && !logout){
					//   // if(WebIM.conn.autoReconnectNumTotal < WebIM.conn.autoReconnectNumMax){
					//   // 	return;
					//   // }
					//   uni.showToast({
					//     title: "websocket 断开",
					//     duration: 1000
					//   });
					//   uni.redirectTo({
					//     url: "../login/login"
					//   });
					//   logout = true;
					//   return;
					// } // 8: offline by multi login

					// if (error.type == WebIM.statusCode.WEBIM_CONNCTION_SERVER_ERROR) {
					//   uni.showToast({
					//     title: "offline by multi login",
					//     duration: 1000
					//   });
					//   uni.redirectTo({
					//     url: "../login/login"
					//   });
					// }

					if (error.type == WebIM.statusCode.WEBIM_CONNCTION_OPEN_ERROR) {
						uni.hideLoading();
						disp.fire("em.error.passwordErr"); // uni.showModal({
						// 	title: "用户名或密码错误",
						// 	confirmText: "OK",
						// 	showCancel: false
						// });
					}

					if (error.type == WebIM.statusCode.WEBIM_CONNCTION_AUTH_ERROR) {
						uni.hideLoading();
						disp.fire("em.error.tokenErr");
					}

					if (error.type == "socket_error") {
						///sendMsgError
						console.log("socket_errorsocket_error", error);
						// uni.showToast({
						// 	title: "网络已断开",
						// 	icon: "none",
						// 	duration: 2000,
						// });
						disp.fire("em.error.sendMsgErr", error);
					}
				},
			});
			this.globalData.checkIsIPhoneX();
		},

		onShow() {
			this.GetVip()
		},
		methods: {
			// 获取vip等级信息，并进行缓存
			GetVip() {
				let that = this
				VIPRateSetting().then((res) => {
					let result = res.data.result
					let params = {}
					for (let i = 0; i < result.length; i++) {
						params[result[i].level] = {
							rate: result[i].rechargeRule,
							name: result[i].name,
							money: result[i].money,
							content: result[i].content,
						}
					}
					storage.setVipRate(params);
					that.viprate = params
				})
			},
			/**
			 * 微信小程序版本提交更新版本 解决缓存问题
			 */
			applyUpdateWeChat() {
				const updateManager = uni.getUpdateManager();

				updateManager.onCheckForUpdate(function(res) {
					// 请求完新版本信息的回调
				});

				updateManager.onUpdateReady(function(res) {
					uni.showModal({
						title: "更新提示",
						content: "发现新版本，是否重启应用？",
						success(res) {
							if (res.confirm) {
								// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
								updateManager.applyUpdate();
							}
						},
					});
				});
				updateManager.onUpdateFailed(function(res) {
					// 新的版本下载失败
				});
			},

			//  TODO 开屏广告 后续优化添加
			launch() {
				try {
					// 获取本地存储中launchFlag标识 开屏广告
					const value = uni.getStorageSync("launchFlag");
					if (!value) {
						// this.$u.route("/pages/index/agreement");
					} else {
						//app启动时打开启动广告页
						var w = plus.webview.open(
							"/hybrid/html/advertise/advertise.html",
							"本地地址", {
								top: 0,
								bottom: 0,
								zindex: 999,
							},
							"fade-in",
							500
						);
						//设置定时器，4s后关闭启动广告页
						setTimeout(function() {
							plus.webview.close(w);
							APPUpdate();
						}, 3000);
					}
				} catch (e) {
					// error
					uni.setStorage({
						key: "launchFlag",
						data: true,
						success: function() {
							console.log("error时存储launchFlag");
						},
					});
				}
			},

			/**
			 * 获取粘贴板数据
			 */
			async getClipboard() {
				let res = await getClipboardData();
				/**
				 * 解析粘贴板数据
				 */
				if (res.indexOf(config.shareLink) != -1) {
					uni.showModal({
						title: "提示",
						content: "检测到一个分享链接是否跳转？",
						confirmText: "跳转",
						success: function(callback) {
							if (callback.confirm) {
								const path = res.split(config.shareLink)[1];
								if (path.indexOf("tabbar") != -1) {
									uni.switchTab({
										url: path,
									});
								} else {
									uni.navigateTo({
										url: path,
									});
								}
							}
						},
					});
				}
			},

			/**
			 * h5中打开app获取跳转app的链接并跳转
			 */
			checkArguments() {
				// #ifdef APP-PLUS
				setTimeout(() => {
					const args = plus.runtime.arguments;
					if (args) {
						const argsStr = decodeURIComponent(args);
						const path = argsStr.split("//")[1];
						if (path.indexOf("tabbar") != -1) {
							uni.switchTab({
								url: `/${path}`,
							});
						} else {
							uni.navigateTo({
								url: `/${path}`,
							});
						}
					}
				});
				// #endif
			},
		},
	};
</script>

<style lang="scss">
	@import "uview-ui/index.scss";

	// -------适配底部安全区  苹果x系列刘海屏

	// #ifdef MP-WEIXIN
	.mp-iphonex-bottom {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		box-sizing: content-box;
		height: auto !important;
		padding-top: 10rpx;
	}

	// #endif

	body {
		background-color: $bg-color;
	}

	/************************ */
	.w200 {
		width: 200rpx !important;
	}

	.flex1 {
		flex: 1; //必须父级设置flex
	}

	.hb-image {
		height: 36upx !important;
		width: 96upx !important;
		margin-right: 8upx;
		vertical-align: middle;
	}

	.hb-money {
		vertical-align: middle;
		color: $main-color;

		.price {
			vertical-align: baseline;
		}
	}

	.hb-line-through {
		display: inline-block;
		margin-left: 8upx;
		vertical-align: middle;
		text-decoration: line-through;
		font-size: 26upx;
		color: #aaaaaa !important;
	}

	.money-format {
		display: flex;
		align-items: flex-end;
		font-size: 26upx;
		height: 26upx;
		line-height: 26upx;

		.zheng {
			font-size: 32upx;
			height: 32upx;
			line-height: 33upx;
			font-weight: bold;
		}

		.xiao,
		.logo {
			font-size: 24upx;
			height: 24upx;
			line-height: 24upx;
			font-weight: bold;
		}
	}

	.u-empty {
		padding-top: 200upx;
	}
</style>
